package cn.bby.tools.utils;

import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;

/**
 * @description: SimpleEditorUtil
 * @author: bby
 * @date: 2025/11/7 11:39
 * @version: 1.0
 */
public class SimpleEditorUtil {

    /**
     * 替换选中的文本
     *
     * @return true-替换成功
     */
    public static boolean replaceSelect(Project project, String text) {

        com.intellij.openapi.editor.Editor editor = com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project)
                .getSelectedTextEditor();
        if (editor != null) {
            WriteCommandAction.runWriteCommandAction(project, () -> {
                // 获取结果文本并插入到当前光标位置
                com.intellij.openapi.editor.Document document = editor.getDocument();
                // 获取当前选中的文本范围
                com.intellij.openapi.editor.SelectionModel selectionModel = editor.getSelectionModel();
                int startOffset = selectionModel.getSelectionStart();
                int endOffset = selectionModel.getSelectionEnd();

                // 替换选中的文本为结果文本
                document.replaceString(startOffset, endOffset, text);

                // 取消选中状态
                selectionModel.removeSelection();
                // 操作完成后关闭对话框
            });
            return true;
        }
        return false;
    }
}
